package model

import (
	"ginTea/structs"
	"ginTea/utils/errmsg"
	"ginTea/utils/helpers"
	"time"

	"github.com/jinzhu/gorm"
)

type Goods struct {
	ID             uint      `gorm:"primary_key" json:"id"`
	CreatedAt      time.Time `json:"created_at" gorm:"column:created_at;autoCreateTime"`
	UpdatedAt      time.Time `json:"updated_at" gorm:"column:updated_at;autoCreateTime"`
	Category       Category  `gorm:"foreignkey:CategoryId" json:"category"`
	Title          string    `gorm:"not null" json:"title"`
	SubTitle       string    `gorm:"column:sub_title" json:"sub_title"`
	CategoryId     int       `gorm:"not null" json:"category_id"`
	Desc           string    `gorm:"not null" json:"desc"`
	ImageUrl       string    `gorm:"not null" json:"image_url"`
	Stock          int       `gorm:"not null" json:"stock"`
	SalesVolume    int       `gorm:"column:sales_volume" json:"sales_volume"`
	OriginalPrice  float32   `gorm:"not null" json:"original_price"`
	CurrentPrice   float32   `gorm:"not null" json:"current_price"`
	IsOnShelf      int       `gorm:"not null" json:"is_onShelf"`
	BirthPlace     string    `gorm:" not null" json:"birth_place"`
	Characteristic string    `gorm:" not null" json:"characteristic"`
}

// 新增商品
func CreateGoods(data *Goods) int {
	err := db.Create(&data).Error
	if err != nil {
		return errmsg.ERROR
	} else {
		return errmsg.SUCCESS
	}
}

// 删除商品
func DeleteGoods(id int) int {
	var data Goods
	db.Select("id").Where("id=?", id).First(&data)
	if data.ID > 0 {
		err := db.Unscoped().Where("id = ?", id).Delete(&data).Error
		if err != nil {
			return errmsg.ERROR
		}
		return errmsg.SUCCESS
	}
	return errmsg.ERROR_GOODS_NOT_EXIST
}

/*
获取所有商品
pageNum 当前页号
pageSize当前页大小
*/
func GetGoodsList(page int, pageSize int, keyword string, cid int) structs.JSONResponse {
	// var goodsList []Goods
	var test []Goods
	var total int
	var list []interface{}
	tx := db.Model(&test).Where("ID >0")
	if len(keyword) > 0 {
		tx = tx.Where("title LIKE ?", "%"+keyword+"%")
	}
	if cid > 0 {
		tx = tx.Where("category_id = ?", cid)
	}
	tx = tx.Preload("Category")
	tx.Count(&total)
	err := tx.Order("id desc").
		Limit(pageSize).
		Offset((page - 1) * pageSize).
		Find(&test).
		RecordNotFound()
	if err {
		return helpers.Error("")
	}
	for _, v := range test {
		list = append(list, v)
	}
	pageData := structs.NewPageData(list, pageSize, page, total)
	response := helpers.Success(pageData)
	return response
}

// 获取某个分类下的所有商品
func GetGoodsByCategoryId(page int, pageSize int, id int) structs.JSONResponse {
	var catGoodsList []Goods
	var total int
	var list []interface{}
	tx := db.Model(&catGoodsList).Where("category_id = ?", id)
	tx = tx.Preload("Category")
	tx.Count(&total)
	err := tx.Find(&catGoodsList).
		Limit(pageSize).
		Offset((page - 1) * pageSize).
		RecordNotFound()
	if err {
		return helpers.Error("")
	}
	for _, v := range catGoodsList {
		list = append(list, v)
	}
	pageData := structs.NewPageData(list, pageSize, page, total)
	response := helpers.Success(pageData)
	return response

}

// 获取商品详情
func GetGoodsInfo(id int) ([]Goods, int) {
	var goodsInfo []Goods
	err := db.Preload("Category").Where("id=?", id).First(&goodsInfo).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, errmsg.ERROR_GOODS_NOT_EXIST
	}
	return goodsInfo, errmsg.SUCCESS
}

// 编辑商品
func UpdateGoods(id int, data *Goods) int {
	var goods Goods
	var maps = make(map[string]interface{})
	maps["title"] = data.Title
	maps["sub_title"] = data.SubTitle
	maps["desc"] = data.Desc
	maps["stock"] = data.Stock
	maps["sales_volume"] = data.SalesVolume
	maps["original_price"] = data.OriginalPrice
	maps["current_price"] = data.CurrentPrice
	maps["category_id"] = data.CategoryId
	maps["is_onShelf"] = data.IsOnShelf
	maps["image_url"] = data.ImageUrl
	maps["birth_place"] = data.BirthPlace
	maps["characteristic"] = data.Characteristic
	err := db.Model(&goods).Where("id = ?", id).Updates(maps).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}
